package com.github.postsanf.yinian.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Color;
import android.media.ExifInterface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.FrageActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.activity.pop.PopListImageDirNew;
import com.github.postsanf.yinian.adapter.LocalManageImageSelAdapter;
import com.github.postsanf.yinian.bean.YNFileComparator;
import com.github.postsanf.yinian.bean.YNFileInfo;
import com.github.postsanf.yinian.bean.YNImageFloder;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.fragment.CameraAlbumFragment;
import com.github.postsanf.yinian.fragment.LatelyAlbumFragment;
import com.github.postsanf.yinian.utils.DisplayUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

public class ImageLocalSelectActivity extends FrageActivity implements PopListImageDirNew.OnImageDirSelected, View.OnClickListener {
    private PopListImageDirNew mListImageDirPopupWindow;
    private GridView mGirdViewtop;
    private LocalManageImageSelAdapter topAdapter;
    private ProgressDialog mProgressDialog;
    private int mPicsSize;
    private File mImgDir;
    public static List<String> mImgs = new ArrayList<>();
    private List<String> mfristImgsnew = new ArrayList<>();
    private ImageView iv_btn_expend_switch;
    private RelativeLayout layout_down;
    private LinearLayout down;
    private RelativeLayout rl_pop_top;
    private ImageView down_title_cover;
    private ImageView title_cover;
    private TextView cameraAlbum;// 相机胶卷
    private TextView lately;// 最近
    private TextView tv_album_name_show;
    private HashSet<String> mDirPaths = new HashSet<String>();
    private List<YNImageFloder> mImageFloders = new ArrayList<YNImageFloder>();
    private List<YNImageFloder> mImageFlodersnew = new ArrayList<YNImageFloder>();
    private CameraAlbumFragment cameraAlbumFragment;
    private LatelyAlbumFragment latelyAlbumFragment;
    public static boolean mainImage = false;
    private long fristtime = 0;
    public static boolean IsSmall = false;
    private TextView tv_next;
    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0x110:
                    data2View();
                    break;
                case 1:
                    if (mProgressDialog != null)
                        mProgressDialog.dismiss();
                    initListDirPopupWindw();
                    sendBroadcast(new Intent("updatebuttomgridview"));
                    break;
            }
        }
    };

    public static boolean fromfrist = false;
    public static int fromfristgid = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        fristtime = System.currentTimeMillis();
        registerBoradcastReceiver();
        setContentView(R.layout.yn_activity_local_select);
        initView();
        getImages();
    }

    private void initView() {
        tv_next = (TextView) findViewById(R.id.tv_next);
        if (getIntent() != null) {
            mainImage = getIntent().getBooleanExtra("mainImage", false);
            fromfrist = getIntent().getBooleanExtra("fromfrist", false);
            fromfristgid = getIntent().getIntExtra("gid", 0);
        }
        if (!mainImage) {
            tv_next.setVisibility(View.GONE);
        } else {
            tv_next.setVisibility(View.VISIBLE);
        }
        findViewById(R.id.iv_back).setOnClickListener(this);
        tv_next.setOnClickListener(this);
        cameraAlbum = (TextView) findViewById(R.id.cameraAlbum);
        lately = (TextView) findViewById(R.id.lately);
        cameraAlbum.setOnClickListener(this);
        lately.setOnClickListener(this);
        cameraAlbumFragment = new CameraAlbumFragment();
        latelyAlbumFragment = new LatelyAlbumFragment();
        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.fl_contaier, cameraAlbumFragment).add(R.id.fl_contaier, latelyAlbumFragment)
                .show(cameraAlbumFragment).hide(latelyAlbumFragment).commit();
        tv_album_name_show = (TextView) findViewById(R.id.tv_album_name_show);
        mGirdViewtop = (GridView) findViewById(R.id.gv_image_top);
        topAdapter = new LocalManageImageSelAdapter(ImageLocalSelectActivity.this, R.layout.yn_image_grid_item_sel);
        mGirdViewtop.setAdapter(topAdapter);
        rl_pop_top = (RelativeLayout) findViewById(R.id.rl_pop_top);
        layout_down = (RelativeLayout) findViewById(R.id.layout_down);
        down = (LinearLayout) findViewById(R.id.down);
        title_cover = (ImageView) findViewById(R.id.title_cover);
        down_title_cover = (ImageView) findViewById(R.id.down_title_cover);
        layout_down.setOnClickListener(this);
        title_cover.setOnClickListener(this);
        down_title_cover.setOnClickListener(this);
        iv_btn_expend_switch = (ImageView) findViewById(R.id.iv_btn_expend_switch);
        findViewById(R.id.ll_album_title_btn).setOnClickListener(this);

    }

    private void data2View() {
        if (mImgDir == null) {
            showToast("图片没扫描到");
            if (mProgressDialog != null)
                mProgressDialog.dismiss();
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int j = 0; j < mImageFloders.size(); j++) {
                    mImgDir = new File(mImageFloders.get(j).getDir());
                    File[] files = mImgDir.listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (file.length() > 0 && !filename.contains(".9")) {
                                if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                        || filename.endsWith(".jpeg") || filename.endsWith(".gif"))
                                    return true;
                            }
                            return false;
                        }
                    });
                    if (files != null) {
                        for (int k = 0; k < files.length; k++) {
                            mfristImgsnew.add(files[k].getAbsolutePath());
                        }
                    }
                }
                ArrayList<YNFileInfo> fileList = new ArrayList<>();
                for (int i = 0; i < mfristImgsnew.size(); i++) {
                    File file = new File(mfristImgsnew.get(i));
                    double imgLat = 0.0, imgLong = 0.0;
                    float[] arr = new float[2];
                    try {
                        imgLat = arr[0];
                        imgLong = arr[1];
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (file.length() > 0) {
                        YNFileInfo fileInfo = new YNFileInfo();
                        fileInfo.setName(file.getName());
                        fileInfo.setPath(file.getAbsolutePath());
                        fileInfo.setLatitude(imgLat);
                        fileInfo.setLongitude(imgLong);
                        fileInfo.setLastModified(file.lastModified());
                        fileList.add(fileInfo);
                    }
                }
                Collections.sort(fileList, new YNFileComparator());
                mImgs.clear();
                for (int j = 0; j < fileList.size(); j++) {
                    mImgs.add(fileList.get(j).getPath());
                }
                mHandler.sendEmptyMessage(1);
            }
        }).start();
    }

    private void initListDirPopupWindw() {
        YNImageFloder imageFloder = new YNImageFloder();
        imageFloder.setDir("所有图片");
        imageFloder.setCount(mImgs.size());
        if (mImgs.size() > 0) {
            imageFloder.setFirstImagePath(mImgs.get(0));
            mImageFlodersnew.add(imageFloder);
        }
        mImageFlodersnew.addAll(mImageFloders);
        mListImageDirPopupWindow = new PopListImageDirNew(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT,
                mImageFlodersnew, LayoutInflater.from(getApplicationContext())
                .inflate(R.layout.yn_album_list_dir, null));
        mListImageDirPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                iv_btn_expend_switch.setImageResource(R.drawable.btn_expend);
            }
        });
        mListImageDirPopupWindow.setOnImageDirSelected(this);
    }

    private void getImages() {
        if (!Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            showToast("暂无外部存储");
            return;
        }
        mProgressDialog = new ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT);
        mProgressDialog.setTitle("");
        mProgressDialog.setMessage(CommonConstants.TIP_LOAD_DATA);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                String firstImage = null;
                Cursor mCursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                        MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                        new String[]{"image/jpeg", "image/png", "image/gif"},
                        MediaStore.Images.Media.DATE_MODIFIED);
                if (mCursor == null)
                    return;
                while (mCursor.moveToNext()) {
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    if (firstImage == null)
                        firstImage = path;
                    File parentFile = new File(path).getParentFile();
                    if (parentFile == null)
                        continue;
                    String dirPath = parentFile.getAbsolutePath();
                    YNImageFloder imageFloder = null;
                    if (mDirPaths.contains(dirPath)) {
                        continue;
                    } else {
                        mDirPaths.add(dirPath);
                        imageFloder = new YNImageFloder();
                        imageFloder.setDir(dirPath);
                        imageFloder.setFirstImagePath(path);
                    }
                    File[] pics = new File(dirPath).listFiles(new FileFilter() {
                        @Override
                        public boolean accept(File file) {
                            String filename = file.getName().toLowerCase();
                            if (filename.toLowerCase().endsWith(".gif") || filename.toLowerCase().endsWith(".jpg") || filename.toLowerCase().endsWith(".png")
                                    || filename.toLowerCase().endsWith(".jpeg"))
                                return true;
                            return false;
                        }
                    });
                    int picSize = (pics != null) ? pics.length : 0;
                    imageFloder.setCount(picSize);
                    mImageFloders.add(imageFloder);
                    if (picSize > mPicsSize) {
                        mPicsSize = picSize;
                        mImgDir = parentFile;
                    }
                }
                mCursor.close();
                mDirPaths = null;
                mHandler.sendEmptyMessage(0x110);
            }
        }).start();
    }

    @Override
    public void selected(YNImageFloder floder) {
        ArrayList<YNFileInfo> fileList = new ArrayList<>();
        fileList.clear();
        File[] files = null;
        if (floder.getDir().equals("所有图片")) {
            files = new File[mfristImgsnew.size()];
            for (int i = 0; i < mfristImgsnew.size(); i++) {
                files[i] = new File(mfristImgsnew.get(i));
            }
        } else {
            mImgDir = new File(floder.getDir());
            files = mImgDir.listFiles(new FileFilter() {
                @Override
                public boolean accept(File file) {
                    String filename = file.getName().toLowerCase();
                    if (file.length() > 0 && !filename.contains(".9")) {
                        if (filename.endsWith(".jpg") || filename.endsWith(".png")
                                || filename.endsWith(".jpeg") || filename.endsWith(".gif"))
                            return true;
                    }
                    return false;
                }
            });
        }
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            String imgPath = file.getAbsolutePath();
            double imgLat = 0.0, imgLong = 0.0;
            boolean flag = true;
            float[] arr = new float[2];
            try {
                ExifInterface exifInterface = new ExifInterface(imgPath);
                flag = exifInterface.getLatLong(arr);
                imgLat = arr[0];
                imgLong = arr[1];
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (file.length() > 0) {
                YNFileInfo fileInfo = new YNFileInfo();
                fileInfo.setName(file.getName());
                fileInfo.setPath(file.getAbsolutePath());
                fileInfo.setLatitude(imgLat);
                fileInfo.setLongitude(imgLong);
                fileInfo.setLastModified(file.lastModified());
                fileList.add(fileInfo);
            }
        }
        Collections.sort(fileList, new YNFileComparator());
        mImgs.clear();
        for (int j = 0; j < fileList.size(); j++) {
            mImgs.add(fileList.get(j).getPath());
        }
        sendBroadcast(new Intent("updatebuttomgridview"));
        tv_album_name_show.setText(floder.getName());
        mListImageDirPopupWindow.dismiss();
    }

    boolean bb = false;

    public void ToSetDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setCancelable(false);
        final AlertDialog dlg = builder.create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.pub_dialog);
        window.setBackgroundDrawableResource(R.color.transparent);
        WindowManager.LayoutParams layout = dlg.getWindow().getAttributes();
        layout.width = DisplayUtils.getScreenWidthPixels(this) - DisplayUtils.dp2px(this, 35 * 2);
        dlg.getWindow().setAttributes(layout);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("提示");
        TextView content = (TextView) window.findViewById(R.id.pp_content);
        content.setText("是否放弃编辑?");
        TextView cancel = (TextView) window
                .findViewById(R.id.btn_cancel);
        cancel.setText("继续编辑");
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView ok = (TextView) window.findViewById(R.id.btn_ok);
        ok.setText("确定");
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (!mainImage) {
            sendBroadcast(new Intent("updateImageNum"));
            finish();
        } else {
            if (new Long(System.currentTimeMillis() - fristtime) > 4900) {
                ToSetDialog();
            } else {
                finish();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                if (!mainImage) {
                    sendBroadcast(new Intent("updateImageNum"));
                    finish();
                } else {
                    if (new Long(System.currentTimeMillis() - fristtime) > 4900) {
                        ToSetDialog();
                    } else {
                        finish();
                    }
                }
                break;
            case R.id.tv_next:
                if (SelectedImg.mSelectedImage.size() == 0) {
                    Toast.makeText(this, "至少选择一张图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                intent2Activity(ImageLocalEditActivity.class);
                break;
            case R.id.layout_down:
                if (!bb) {
                    bb = true;
                    Animation translateAnimation = new TranslateAnimation(0, 0, 0, -UIHelper.dip2px(ImageLocalSelectActivity.this, 260));
                    translateAnimation.setDuration(400);
                    down.startAnimation(translateAnimation);
                    translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            sendBroadcast(new Intent("topgridviewclose"));
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                    AlphaAnimation alphaAnimationcover = new AlphaAnimation(0.0f, 1.0f);
                    alphaAnimationcover.setDuration(400);
                    title_cover.startAnimation(alphaAnimationcover);
                    title_cover.setVisibility(View.VISIBLE);
                    down_title_cover.setVisibility(View.VISIBLE);
                } else {
                    bb = false;
                    Animation translateAnimation = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(ImageLocalSelectActivity.this, 260));
                    translateAnimation.setDuration(400);
                    down.startAnimation(translateAnimation);
                    translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                        @Override
                        public void onAnimationStart(Animation animation) {
                        }

                        @Override
                        public void onAnimationEnd(Animation animation) {
                            sendBroadcast(new Intent("topgridviewopen"));
                        }

                        @Override
                        public void onAnimationRepeat(Animation animation) {
                        }
                    });
                }
                break;
            case R.id.ll_album_title_btn:
                iv_btn_expend_switch.setImageResource(R.drawable.btn_expend_up);
                if (mListImageDirPopupWindow != null) {
                    mListImageDirPopupWindow.showAsDropDown(rl_pop_top, 0, 0);
                }
                break;
            case R.id.cameraAlbum:
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.show(cameraAlbumFragment).hide(latelyAlbumFragment).commit();
                cameraAlbum.setTextColor(Color.parseColor("#000000"));
                lately.setTextColor(Color.parseColor("#aeaeae"));
                break;
            case R.id.lately:
                FragmentTransaction transaction2 = getSupportFragmentManager().beginTransaction();
                transaction2.show(latelyAlbumFragment).hide(cameraAlbumFragment).commit();
                lately.setTextColor(Color.parseColor("#000000"));
                cameraAlbum.setTextColor(Color.parseColor("#aeaeae"));
                sendBroadcast(new Intent("updatebuttomgridview"));
                break;
            case R.id.title_cover:
            case R.id.down_title_cover:
                bb = false;
                AlphaAnimation alphaAnimationcover = new AlphaAnimation(1.0f, 0.0f);
                alphaAnimationcover.setDuration(400);
                title_cover.startAnimation(alphaAnimationcover);
                down_title_cover.startAnimation(alphaAnimationcover);
                alphaAnimationcover.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        title_cover.setVisibility(View.GONE);
                        down_title_cover.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                Animation translateAnimation = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(ImageLocalSelectActivity.this, 260));
                translateAnimation.setDuration(400);
                down.startAnimation(translateAnimation);
                translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        sendBroadcast(new Intent("topgridviewopen"));
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                break;
        }
    }


    // 清除选中并退出
    private void clearAll() {
        SelectedImg.mSelectedImage.clear();
        finish();
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionCloseAlbum:
                    int noClear = intent.getExtras().getInt(ACTIONs.aIsClearSelect);
                    if (1 == noClear) {
                        finish();
                    } else {
                        clearAll();
                    }
                    break;
                case ACTIONs.actionUpdateUpNum:
                    break;
                case "updatetopgridview":
                    Log.i("xjs", "updatetopgridview");
                    topAdapter.notifyDataSetChanged();
                    break;
                case "topgridviewclose":
                    mGirdViewtop.setVisibility(View.GONE);
                    break;
                case "topgridviewopen":
                    AlphaAnimation alphaAnimationtop = new AlphaAnimation(0.0f, 1.0f);
                    alphaAnimationtop.setDuration(700);
                    mGirdViewtop.startAnimation(alphaAnimationtop);
                    mGirdViewtop.setVisibility(View.VISIBLE);
                    break;
            }
        }
    };

    //注册广播
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionUpdateUpNum);
        myIntentFilter.addAction("updatetopgridview");
        myIntentFilter.addAction("topgridviewopen");
        myIntentFilter.addAction("topgridviewclose");
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        if (mainImage) {
            SelectedImg.mSelectedImage.clear();
            AiteSelectActivity.phoneNames.clear();
            MicAddActivity.mMp3FileName = "";
            MainActivity.mp3IsExist = false;
            MainActivity.micUrl = "";
            MainActivity.micpath = "";
            MainActivity.locationTx = "";
        }
        this.unregisterReceiver(mBroadcastReceiver);
        if (mProgressDialog != null)
            mProgressDialog.dismiss();
        super.onDestroy();
    }


    public void onResume() {
        super.onResume();
        topAdapter.notifyDataSetChanged();
        sendBroadcast(new Intent("updatebuttomgridview"));
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
    }
}
